/*
 * Basic no frills app which integrates the ZBar barcode scanner with
 * the camera.
 * 
 * Created by lisah0 on 2012-02-24
 */
package com.darryring.fast.activitys;


import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.res.TypedArray;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;

import com.darryring.fast.R;
import com.darryring.fast.base.BaseAppCompatActivity;
import com.darryring.fast.theme.FastTheme;
import com.darryring.libcore.Fast;
import com.darryring.libmodel.entity.theme.ThemeEntity;
import com.darryring.libview.LibCameraPreview;

import net.sourceforge.zbar.Config;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;

/**
 * 扫码,扫描二维码
 */
public class ScancodeActivity extends BaseAppCompatActivity {

    private LibCameraPreview mPreview;
    private Handler autoFocusHandler;
    Button scanButton;
    ImageScanner scanner;
    private boolean barcodeScanned = false;
    private boolean previewing = true;

    static {
        System.loadLibrary("iconv");
    }

    private String mResult;
    View animation_line;
    FrameLayout animationFrameLayout;
    AnimatorSet set =null;
    public void onCreate(Bundle savedInstanceState) {
        FastTheme.fastTheme.setupTheme(this, ThemeEntity.TYPE_NO_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_qrcode);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        autoFocusHandler = new Handler();
        /* Instance barcode scanner */
        scanner = new ImageScanner();
        scanner.setConfig(0, Config.X_DENSITY, 3);
        scanner.setConfig(0, Config.Y_DENSITY, 3);
        mPreview = new LibCameraPreview(this, previewCb, autoFocusCB);
        FrameLayout preview = (FrameLayout) findViewById(R.id.cameraPreview);
        preview.addView(mPreview);
        animation_line = findViewById(R.id.animation_line);
        scanButton = (Button) findViewById(R.id.btn_qrcode_scan);
        animationFrameLayout = (FrameLayout) findViewById(R.id.animation_layer);
        scanButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (barcodeScanned) {
                    barcodeScanned = false;
                    mPreview.setPreviewCallback(previewCb);
                    mPreview.startPreview();
                    previewing = true;
                    mPreview.autoFocus(autoFocusCB);
                    scanButton.setVisibility(View.GONE);
                }
            }
        });
        //
        //===============================================================================
        if(FastTheme.fastTheme.theme()!=null){
            TypedArray ta = getTheme().obtainStyledAttributes(R.styleable.FastColorTheme);
            int _selectColor = ta.getColor(R.styleable.FastColorTheme_colorFastNomal,0);
            animation_line.setBackgroundColor(_selectColor);
            ta.recycle();
        }
        //==============================================================================
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == android.R.id.home)
        {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setupScanAnimationLine();
    }

    private void setupScanAnimationLine() {
        if (animation_line != null) {
            set = new AnimatorSet();
            ViewGroup.LayoutParams _params = animationFrameLayout.getLayoutParams();
            ObjectAnimator o1 =  ObjectAnimator.ofFloat(animation_line, "translationY", 0, _params.height);
            o1.setRepeatCount(10000);
            o1.setRepeatMode(ValueAnimator.INFINITE);
            set.play(o1);
            set.setDuration(4 * 1000);
            set.start();
        }
    }

    public void onPause() {
        super.onPause();
        if (mPreview != null) {
            mPreview.releaseCamera();
        }
        if(set!=null && set.isStarted()){
            set.cancel();
            set = null;
        }
    }


    private Runnable doAutoFocus = new Runnable() {
        public void run() {
            Fast.logger.i(TAG, "doAutoFocus-->run....");
            if (previewing && mPreview != null) {
                mPreview.autoFocus(autoFocusCB);
            }
        }
    };

    PreviewCallback previewCb = new PreviewCallback() {
        public void onPreviewFrame(byte[] data, Camera camera) {
            Parameters parameters = camera.getParameters();
            Size size = parameters.getPreviewSize();

            Image barcode = new Image(size.width, size.height, "Y800");
            barcode.setData(data);

            int result = scanner.scanImage(barcode);

            if (result != 0) {
                previewing = false;
                mPreview.setPreviewCallback(null);
                mPreview.stopPreview();
                SymbolSet syms = scanner.getResults();
                for (Symbol sym : syms) {
                    mResult = sym.getData();
                    barcodeScanned = true;
                }
            }
        }
    };
    String TAG = "ScancodeActivity";
    // Mimic continuous auto-focusing
    AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
        public void onAutoFocus(boolean success, Camera camera) {
            Fast.logger.i(TAG, "autoFocusCB-->onAutoFocus-->" + success);
            autoFocusHandler.postDelayed(doAutoFocus, 1000);
        }
    };


}
